package com.leyou.user.controller;

import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    //校验用户名或手机号
    @GetMapping("/check/{data}/{type}")
    @ApiOperation("校验用户名或手机号是否可用，不存在即为可用")
    @ApiResponses({
            @ApiResponse(code=200,message = "参数正确，返回true或false,表示用户不存在或存在"),
            @ApiResponse(code=204,message = "参数错误，type不是1或2")
    })
    public ResponseEntity<Boolean> checkUserData(
            @ApiParam(value = "要校验的数据",example = "lisi") @PathVariable("data")String data,
            @ApiParam(value = "数据类型：1：用户名，2：手机号") @PathVariable("type")Integer type     //类型：1、用户名，2、手机
    ){

         return ResponseEntity.ok(userService.checkData(data,type));
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册业务
     * 传入参数：username,password,phone,code
     *
     * @param user
     * @param code
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code) {
        if (result.hasErrors()){
            String msg = result.getFieldErrors().stream().
                    map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            throw new LyException(msg,400);
        }

        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    @GetMapping("query")
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username, @RequestParam("password") String password){
        return ResponseEntity.ok(userService.queryUserByUsernameAndPassword(username, password));
    }
}
